var EARTH_RADIUS = 6378137.0;    //单位M
var PI = Math.PI;
     
function getRad(d) {
    return d*PI/180.0;
}


/**
 * approx distance between two points on earth ellipsoid （Flattern）
 * @param {Object} p1: [0]-latitude [1]-lontitude
 * @param {Object} p2: [0]-latitude [1]-lontitude
 */
function getDistance(p1, p2) {

    //计算弧度
    var f = getRad((p1[0] + p2[0])/2);
    var g = getRad((p1[0] - p2[0])/2);
    var l = getRad((p1[1] - p2[1])/2);

    //
    var sg = Math.sin(g);
    var sl = Math.sin(l);
    var sf = Math.sin(f);

    var s,c,w,r,d,h1,h2;
    var a = EARTH_RADIUS;
    var fl = 1/298.257;

    sg = sg*sg;
    sl = sl*sl;
    sf = sf*sf;

    s = sg*(1-sl) + (1-sf)*sl;
    c = (1-sg)*(1-sl) + sf*sl;
    w = Math.atan(Math.sqrt(s/c));
    r = Math.sqrt(s*c)/w;
    d = 2*w*a;
    h1 = (3*r -1)/2/c;
    h2 = (3*r +1)/2/s;

    return d*(1 + fl*(h1*sf*(1-sg) - h2*(1-sf)*sg));
}


function zf(a) {
    return Math.PI * a / 180
}

function Go(a, b, c) {
    b != null && (a = Math.max(a, b));
    c != null && (a = Math.min(a, c));
    return a
}

function Bo(a, b, c) {
    for (; a > c;) a -= c - b;
    for (; a < b;) a += c - b;
    return a
}

function Pc(a, b, c, d) {
    var Au = 6370996.81;
    return Au * Math.acos(Math.sin(c) * Math.sin(d) + Math.cos(c) * Math.cos(d) * Math.cos(b - a))
}

function uo(a, b) {
    if (!a || !b) return 0;
    a.lng = Bo(a.lng, -180, 180);
    a.lat = Go(a.lat, -74, 74);
    b.lng = Bo(b.lng, -180, 180);
    b.lat = Go(b.lat, -74, 74);
    return Pc(zf(a.lng), zf(b.lng), zf(a.lat), zf(b.lat))
}

/*
 *获取百度地图两点距离(from baidu)
 * @param a: bd point 
 * @param b: bd point
 * @return : points distance
 */
function getD(a,b) {
    if (a && b) {
        var c = 0;
        return c = uo(a, b)
    }
}